package realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import realtime.bean.CartAddCtBean;
import realtime.bean.TradeOrderCtBean;
import realtime.util.ClickHouseUtil;
import realtime.util.DateFormatUtil;
import realtime.util.MyKafkaUtil;

import java.time.Duration;

public class Dws_Trade_Order_Ct {
    public static void main(String[] args) throws Exception {

        //TODO 1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //TODO 2.读取Kafka DWD层 dwd_trade_order_detail
        DataStreamSource<String> kafkaDS = env.addSource(MyKafkaUtil.getFlinkKafkaConsumer("dwd_trade_order_detail", "dwd_trade_cart_add"));

        kafkaDS.print("kafkaDS>>>>");
        //TODO 3.转换为JSON对象
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaDS.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                JSONObject jsonObject = JSON.parseObject(value);

                out.collect(jsonObject);

            }
        });

        jsonObjDS.print("jsonObjDS>>>");

        //TODO 4.提取时间戳生成Watermark
        SingleOutputStreamOperator<JSONObject> jsonObjWithWMDS = jsonObjDS.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(2)).withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
            @Override
            public long extractTimestamp(JSONObject element, long recordTimestamp) {
                return element.getLong("create_time");
            }
        }));

        //TODO 5.按照uid分组
        KeyedStream<JSONObject, String> keyedStream = jsonObjWithWMDS.keyBy(value -> value.getString("user_id"));

        //TODO 6.转为JavaBean
        SingleOutputStreamOperator<TradeOrderCtBean> javaBeanDS = keyedStream.map(new MapFunction<JSONObject, TradeOrderCtBean>() {
            @Override
            public TradeOrderCtBean map(JSONObject value) throws Exception {
                return new TradeOrderCtBean("", "",1L,null);
            }
        });

        javaBeanDS.print("JBDS>>>>>");

        //TODO 7.开窗、聚合
        SingleOutputStreamOperator<TradeOrderCtBean> resultDS = javaBeanDS.windowAll(TumblingEventTimeWindows.of(Time.seconds(10)))
                .reduce(new ReduceFunction<TradeOrderCtBean>() {
                    @Override
                    public TradeOrderCtBean reduce(TradeOrderCtBean value1, TradeOrderCtBean value2) throws Exception {
                        value1.setOrderCt(value1.getOrderCt() + value2.getOrderCt());
                        return value1;
                    }
                }, new AllWindowFunction<TradeOrderCtBean, TradeOrderCtBean, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window, Iterable<TradeOrderCtBean> values, Collector<TradeOrderCtBean> out) throws Exception {
                        TradeOrderCtBean next = values.iterator().next();

                        next.setTs(System.currentTimeMillis());
                        next.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));
                        next.setStt(DateFormatUtil.toYmdHms(window.getStart()));

                        out.collect(next);
                    }
                });

        //TODO 8.写出数据
//        resultDS.print("resultDS>>>>");
        resultDS.addSink(ClickHouseUtil.getSinkFunction("insert into dws_trade_order_window values(?,?,?,?)"));

        //TODO 9.启动任务
        env.execute("Dws_Trade_Order_Ct");
    }
}
